//------------------------------------------------------------------------------
// X2D Game Engine
// Copyright (C) 2006-2007 Janusz Kowalski
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//------------------------------------------------------------------------------

#include <cstring>
#include <fstream>


#include "x2d_Anim.h"
#include "x2d_ext.h"
#include "pmsg.h"
#include "os.h"

namespace x2d {

Anim::Anim() { }

Anim::~Anim() { }

SDL_Surface *Anim::getSurf() {
  return 0;
}

static const int ANIFILE_LINE_MAXLENGTH = 256;

FrameAnim::FrameAnim() {
  startTime_ = SDL_GetTicks(); total_=0;
}

FrameAnim::FrameAnim(const char *path) {
  startTime_ = SDL_GetTicks(); total_=0;
  load(path);
}

void FrameAnim::load(const char *path) {
  const unsigned BUFFER_SIZE=256;
  std::ifstream file(path);
  
  int afterSlash = 0;
  
  for(int i=0; path[i]!=0; i++) if(path[i]=='/') afterSlash = i+1;
  
  while(file.good()) {
    char imgPath[BUFFER_SIZE];
    // !! We do not need to copy each time.
    stringCopyN(imgPath, BUFFER_SIZE, path, afterSlash);
    file.width(BUFFER_SIZE-afterSlash);
    file >> (imgPath+afterSlash);
    int duration;
    file >> duration;

    Image img(imgPath);
    frame_.add(img);
    duration_.add(duration);
    total_+=duration;
  }
}

SDL_Surface *FrameAnim::getSurf() {
  int shift = (SDL_GetTicks()-startTime_)%total_;
  for(unsigned i=0; i<frame_.size(); i++) {
    shift-=duration_[i];
    if(shift<0) return frame_[i].getSurf();
  }
  ASSURE(0);
  return 0;
}

Image& FrameAnim::getImage() {
  int shift = (SDL_GetTicks()-startTime_)%total_;
  for(unsigned i=0; i<frame_.size(); i++) {
    shift-=duration_[i];
    if(shift<0) return frame_[i];
  }
  ASSURE(0);
}

NoAnim::NoAnim(const char *path) : img_(path) {
}

SDL_Surface *NoAnim::getSurf() {
  return img_.getSurf();
}

Image& NoAnim::getImage() {
  return img_;
}

} // namespace x2d
